/***********************************************************
 *
 * Gaoth
 * Copyright (c) 2011- Marcus Lundgren
 *
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from
 * the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it freely,
 * subject to the following restrictions:
 *
 *  1. The origin of this software must not be misrepresented; you must not
 *     claim that you wrote the original software. If you use this software
 *     in a product, an acknowledgment in the product documentation would be
 *     appreciated but is not required.
 *
 *  2. Altered source versions must be plainly marked as such,
 *     and must not be misrepresented as being the original software.
 *
 *  3. This notice may not be removed or altered from any source distribution.
 *
 ***********************************************************/

#include "network_manager.h"

#include <iostream>
#include <string>
#include <sstream>

#define DEFAULT_PORT 4567

NetworkManager::NetworkManager( Model* model )
: _model( model )
{

}

NetworkManager::~NetworkManager()
{
    _listener.disconnect();
    _model = 0;
}

void NetworkManager::connect( const sf::IpAddress& address )
{
    if( _listener.connect( address, DEFAULT_PORT ) )
        std::cout << "Connected to the server!\n";
}

void NetworkManager::send( const gth::shared::network::BasePayload& payload )
{
    sf::Packet p;
    payload.to_packet(p);
    _listener.send( p );
}

void NetworkManager::update()
{
    sf::Packet packet;
    if( _listener.receive( packet ) == sf::Socket::Done )
    {
        std::auto_ptr<gth::shared::network::BasePayload> payload = _pkt_mgr.parse_packet(packet);
        //std::cout << "Got <" << ((gth::shared::network::LoginPayload*) payload.get())->name << "> from the server!\n";
        _model->entities = ((gth::shared::network::ModelPayload*) payload.get())->entities;
        /*_model->entities.clear();
        std::vector<gth::shared::data::BaseEntity> &entities = ((gth::shared::network::ModelPayload*) payload.get())->entities;
        for( std::vector<gth::shared::data::BaseEntity>::iterator it = entities.begin() ; it != entities.end() ; ++it )
            _model->entities.push_back( *it );*/
        //_model->set_last_message( ((gth::shared::network::LoginPayload*) payload.get())->name );
    }
    // Something went wrong, disconnect the client
    else
    {
    }
}
